<template>
  <a-row :gutter="[12, 0]" class="px-[12px] pt-2 a-row-box">
    <a-col :span="8" class="flex flex-col">
      <Card title="铁路货运" :desc="tlgk.desc" class="h-full flex flex-col">
        <template #desc>
          <span @click="opanDetail('铁路货运')" style="color: #55b8c1; cursor: pointer"
            >（查看明细）
          </span>
          <div>
            <a-select
              v-model:value="tlgk.year"
              :options="utils.genSelectOptions('year')"
              @change="loadTlData(false)"
              size="small"
            />
            <a-select
              class="ml-1"
              v-model:value="tlgk.month"
              :options="utils.genSelectOptions('month')"
              @change="loadTlData(false)"
              size="small"
            />
          </div>
        </template>

        <div class="h-[52px] flex justify-around mt-[12px]">
          <div class="text-center">
            <span class="text-md block">装车车皮总数</span>
            <NumberAnimation
              :value="tlgk.monthStatistics.loadingCarLeatherTotal"
              unit="车"
              class="text-2xl font-bold block"
            >
              <template #suffix></template>
            </NumberAnimation>
          </div>
          <div class="text-center">
            <span class="text-md block">装车总重量</span>
            <NumberAnimation
              :value="tlgk.monthStatistics.loadingTotalWeight"
              unit="吨"
              class="text-2xl font-bold block"
            >
              <template #suffix></template>
            </NumberAnimation>
          </div>
        </div>

        <div class="h-[52px] flex justify-around mt-[12px]">
          <div class="text-center">
            <span class="text-md block">卸车车皮总数</span>
            <NumberAnimation
              :value="tlgk.monthStatistics.unloadCarLeatherTotal"
              unit="车"
              class="text-2xl font-bold block"
            >
              <template #suffix></template>
            </NumberAnimation>
          </div>
          <div class="text-center">
            <span class="text-md block">卸车总重量</span>
            <NumberAnimation
              :value="tlgk.monthStatistics.unloadTotalWeight"
              unit="吨"
              class="text-2xl font-bold block"
            >
              <template #suffix></template>
            </NumberAnimation>
          </div>
        </div>

        <div id="tlhyl" class="w-full h-1/2 mx-auto"></div>
        <div id="tlcpl" class="w-full h-1/2 mx-auto"></div>
      </Card>
    </a-col>

    <a-col :span="8" class="flex flex-col">
      <Card title="航空货运" :desc="hkgk.desc" class="h-1/2 flex flex-col">
        <template #desc>
          <span @click="opanDetail('航空货运')" style="color: #55b8c1; cursor: pointer"
            >（查看明细）
          </span>
          <div class="flex flex-row">
            <a-select
              v-model:value="hkgk.year"
              :options="utils.genSelectOptions('year')"
              @change="loadHkData(false)"
              size="small"
            />
            <a-select
              class="ml-1"
              v-model:value="hkgk.month"
              :options="utils.genSelectOptions('month')"
              @change="loadHkData(false)"
              size="small"
            />
          </div>
        </template>

        <div class="h-[52px] flex justify-around mt-[12px]">
          <div class="text-center">
            <span class="text-md block">货邮吞吐量</span>
            <NumberAnimation
              :value="hkgk.monthStatistics.freightAndThroughput"
              unit="吨"
              class="text-2xl font-bold block"
            >
              <!-- <template #suffix>万</template> -->
            </NumberAnimation>
          </div>
          <div class="text-center">
            <span class="text-md block">同比增幅</span>
            <span class="text-2xl font-bold block">
              <span class="valueNum-zf">
                {{
                  hkgk.freightAndThroughspanutYoy > 0
                    ? `+${hkgk.freightAndThroughputYoy}`
                    : hkgk.freightAndThroughputYoy
                }}
              </span>
              <span class="unit">{{ hkgk.freightAndThroughputYoy == '/' ? '' : '%' }}</span>
            </span>
          </div>
        </div>

        <div id="hkhyttl" class="w-full h-full mx-auto"></div>
      </Card>

      <Card title="公路货运" :desc="glgk.desc" class="h-1/2 flex flex-col mt-[12px]">
        <template #desc>
          <span @click="opanDetail('公路货运')" style="color: #55b8c1; cursor: pointer"
            >（查看明细）
          </span>
          <div class="flex flex-row">
            <a-select
              v-model:value="glgk.year"
              :options="utils.genSelectOptions('year')"
              @change="loadGlData(false)"
              size="small"
            />
            <a-select
              class="ml-1"
              v-model:value="glgk.month"
              :options="utils.genSelectOptions('month')"
              @change="loadGlData(false)"
              size="small"
            />
          </div>
        </template>

        <div class="h-[52px] flex justify-around mt-[12px]">
          <div class="text-center">
            <span class="text-md block">货运量</span>
            <NumberAnimation
              :value="glgk.monthStatistics.theVolume"
              unit="万吨"
              class="text-2xl font-bold block"
            >
              <template #suffix></template>
            </NumberAnimation>
          </div>
          <div class="text-center">
            <span class="text-md block">同比增幅</span>
            <span class="text-2xl font-bold block">
              <span class="valueNum-zf">
                {{ glgk.theVolumeYoy > 0 ? `+${glgk.theVolumeYoy}` : glgk.theVolumeYoy }}
              </span>
              <span class="unit">{{ glgk.theVolumeYoy == '/' ? '' : '%' }}</span>
            </span>
          </div>

          <div class="text-center ml-[32px]">
            <span class="text-md block">货物周转量</span>
            <NumberAnimation
              :value="glgk.monthStatistics.goodsTurnoverVolume"
              unit="万吨公里"
              class="text-2xl font-bold block"
            >
              <template #suffix></template>
            </NumberAnimation>
          </div>
          <div class="text-center">
            <span class="text-md block">同比增幅</span>
            <span class="text-2xl font-bold block">
              <span class="valueNum-zf">
                {{
                  glgk.goodsTurnoverVolumeYoy > 0
                    ? `+${glgk.goodsTurnoverVolumeYoy}`
                    : glgk.goodsTurnoverVolumeYoy
                }}
              </span>
              <span class="unit">{{ glgk.goodsTurnoverVolumeYoy == '/' ? '' : '%' }}</span>
            </span>
          </div>
        </div>
        <div id="glhyl" class="w-full h-full mx-auto"></div>
      </Card>
    </a-col>

    <a-col :span="8" class="flex flex-col">
      <Card title="邮政快递" :desc="yzgk.desc" class="h-1/3 flex flex-col">
        <template #desc>
          <span @click="opanDetail('邮政快递')" style="color: #55b8c1; cursor: pointer"
            >（查看明细）
          </span>
          <div class="flex flex-row">
            <a-select
              v-model:value="yzgk.year"
              :options="utils.genSelectOptions('year')"
              @change="loadYzData(false)"
              size="small"
            />
            <a-select
              class="ml-1"
              v-model:value="yzgk.month"
              :options="utils.genSelectOptions('month')"
              @change="loadYzData(false)"
              size="small"
            />
          </div>
        </template>

        <div class="h-[52px] flex justify-around mt-[12px]">
          <div class="text-center">
            <span class="text-md block">快递业务寄件量</span>
            <NumberAnimation :value="kdywjjl" unit="万件" class="text-2xl font-bold block">
              <template #suffix></template>
            </NumberAnimation>
          </div>
          <div class="text-center">
            <span class="text-md block">邮政普邮寄件量</span>
            <NumberAnimation :value="yzpbfwjjl" unit="万件/万份" class="text-2xl font-bold block">
              <template #suffix></template>
            </NumberAnimation>
          </div>
        </div>

        <div v-if="false" class="h-[52px] flex justify-around mt-[12px]">
          <div class="text-center">
            <span class="text-md block">快递业务收入</span>
            <NumberAnimation :value="803" unit="元" class="text-2xl font-bold block">
              <template #suffix>万</template>
            </NumberAnimation>
          </div>
          <div class="text-center">
            <span class="text-md block">邮政普遍服务收入</span>
            <NumberAnimation :value="11112" unit="元" class="text-2xl font-bold block">
              <template #suffix>万</template>
            </NumberAnimation>
          </div>
        </div>

        <div class="h-[12px]"></div>

        <div id="kdywjjbl" class="w-4/5 h-1/4 mx-auto"></div>

        <div class="h-[12px]"></div>
        <div class="h-[12px]"></div>

        <div id="yzpbfwjjbl" class="w-4/5 h-1/4 mx-auto"></div>

        <div id="yzhyywsr" class="w-full h-1/2 mx-auto"></div>
      </Card>
    </a-col>
  </a-row>

  <!-- 铁路货运量 -->
  <TlhylModal ref="tlhylModalRef" />
  <!-- 铁路车皮量 -->
  <TlcplModal ref="tlcplModalRef" />
  <!-- 航空货邮吞吐量 -->
  <HkttlModal ref="hkttlModalRef" />
  <!-- 公路货运量 -->
  <GlhylModal ref="glhylModalRef" />
  <!-- 邮政行业业务收入 -->
  <YzsyqkModal ref="yzsyqkModalRef" />
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import Card from './card.vue'
import * as echarts from 'echarts'
import { Apis } from '@/api'
import { useBigScreenStore } from '../store'
import NumberAnimation from '@/components/number-animation.vue'
import * as utils from '../utils'
import bigjs from 'big.js'
import TlhylModal from '../modal/logistics/tl-hyl-modal.vue'
import TlcplModal from '../modal/logistics/tl-cpl-modal.vue'
import HkttlModal from '../modal/logistics/hk-ttl-modal.vue'
import GlhylModal from '../modal/logistics/gl-hyl-modal.vue'
import YzsyqkModal from '../modal/logistics/yz-syqk-modal.vue'
import Big from 'big.js'
const emit = defineEmits(['mounted'])
const tlhylModalRef = ref<InstanceType<typeof TlhylModal>>()
const tlcplModalRef = ref<InstanceType<typeof TlcplModal>>()
const hkttlModalRef = ref<InstanceType<typeof HkttlModal>>()
const glhylModalRef = ref<InstanceType<typeof GlhylModal>>()
const yzsyqkModalRef = ref<InstanceType<typeof YzsyqkModal>>()
const bigScreenStore = useBigScreenStore()
const kdywjjl = computed(() => {
  const withCity = yzgk.monthStatistics.withCity || 0
  const remoteLocation = yzgk.monthStatistics.remoteLocation || 0
  const internationalHk = yzgk.monthStatistics.internationalHk || 0
  return new bigjs(withCity).plus(remoteLocation).plus(internationalHk).toNumber()
})
const yzpbfwjjl = computed(() => {
  const orderSalesNewspaper = yzgk.monthStatistics.orderSalesNewspaper || 0
  const letters = yzgk.monthStatistics.letters || 0
  const packageNum = yzgk.monthStatistics.packageNum || 0
  const orderSalesMagazine = yzgk.monthStatistics.orderSalesMagazine || 0
  return new bigjs(orderSalesNewspaper)
    .plus(letters)
    .plus(packageNum)
    .plus(orderSalesMagazine)
    .toNumber()
})
/** 铁路货运 */
const tlgk = reactive({
  year: '',
  month: '',
  desc: '', // 截止2024年12月
  monthStatistics: {
    // 卸车车皮总数
    unloadCarLeatherTotal: 0,
    // 装车车皮总数
    loadingCarLeatherTotal: 0,
    // 装车总重量
    loadingTotalWeight: 0,
    // 卸车总重量
    unloadTotalWeight: 0,

    cpCount: 0,
  },
})

/** 年度货运分类情况 */
const tlhylOptions = reactive({
  title: {
    text: '年度货运分类情况',
    left: 'center',
    top: '10%',
    textStyle: {
      fontSize: 16,
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    formatter: function (params) {
      let result = params[0].name + '<br/>'
      params.forEach((param) => {
        result +=
          param.seriesName +
          ': ' +
          (param.seriesName.includes('车数') ? param.value + '车' : param.value + '吨') +
          '<br/>'
      })
      return result
    },
  },
  legend: {
    show: true,
    orient: 'horizontal',
    bottom: '5%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: ['装车', '卸车', '车数'],
  },
  grid: {
    top: '26%',
    left: '2%',
    right: '2%',
    bottom: '15%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      fontSize: 12,
    },
  },
  yAxis: [
    {
      type: 'value',
      name: '吨',
      position: 'left',
      alignTicks: true,
      axisLabel: {
        formatter: '{value} 吨',
        fontSize: 12,
      },
    },
    {
      type: 'value',
      name: '车',
      position: 'right',
      alignTicks: true,
      axisLabel: {
        formatter: '{value} 车',
        fontSize: 12,
      },
    },
  ],
  series: [
    {
      name: '装车',
      data: [], // 示例数据
      type: 'bar',
      color: '#336bd3',
      barWidth: '30%',
      yAxisIndex: 0, // 明确使用主Y轴（吨）
    },
    {
      name: '卸车',
      data: [], // 示例数据
      type: 'bar',
      color: '#37e0cc',
      barWidth: '30%',
      yAxisIndex: 0, // 使用主Y轴（吨）
    },
    {
      name: '车数',
      data: [], // 示例数据
      type: 'line',
      radius: '100%',
      smooth: true,
      yAxisIndex: 1, // 明确使用次Y轴（车）
      symbolSize: 6,
      color: '#FFA500',
      lineStyle: {
        width: 2,
      },
    },
  ],
})

/** 铁路车皮量(年度货运总量) */
const tlcplOptions = reactive({
  title: {
    ...utils.generateChartTitle('年度货运总量'),
    top: '0%',
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '0%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: [], // '2024年', '2023年'
  },
  grid: {
    top: '26%',
    left: '2%',
    right: '2%',
    bottom: '15%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      fontSize: 12,
    },
  },
  yAxis: {
    type: 'value',
    name: '吨',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  series: [],
})

/** 航空货运 */
const hkgk = reactive({
  year: '',
  month: '',
  desc: '', // 截止2024年12月
  freightAndThroughputYoy: '/', // 货运量同比增长率
  monthStatistics: {
    freightAndThroughput: 0, // 货运量
    qnFreightAndThroughput: 0, // 去年货运量
  },
})

/** 航空货邮吞吐量 */
const hkhyttlOptions = reactive({
  title: {
    text: '吞吐量',
    left: 'center',
    top: '8%',
    textStyle: {
      fontSize: 16,
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '5%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: [],
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    axisLabel: {
      fontSize: 12,
    },
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
  },
  yAxis: {
    type: 'value',
    name: '吨',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  grid: {
    top: '26%',
    left: '2%',
    right: '2%',
    bottom: '15%',
    containLabel: true,
  },
  series: [],
})

/** 公路货运 */
const glgk = reactive({
  year: '',
  month: '',
  desc: '', // 截止2024年12月
  theVolumeYoy: '/', // 货运量同比增长率
  goodsTurnoverVolumeYoy: '/', // 货物周转量同比增长率
  monthStatistics: {
    goodsTurnoverVolume: 0, // 货物周转量（万吨公里）
    qnGoodsTurnoverVolume: 0, // 去年货物周转量（万吨公里）
    theVolume: 0, // 货运量（万吨）
    qnTheVolume: 0, // 去年货运量（万吨）
  },
})

/** 公路货运量 */
const glhylOptions = reactive({
  title: {
    text: '货运量',
    left: 'center',
    top: '8%',
    textStyle: {
      fontSize: 16,
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '5%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: ['2024年', '2023年'],
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    axisLabel: {
      fontSize: 12,
    },
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
  },
  yAxis: {
    type: 'value',
    name: '吨',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  grid: {
    top: '26%',
    left: '2%',
    right: '2%',
    bottom: '15%',
    containLabel: true,
  },
  series: [],
})

/** 邮政概况 */
const yzgk = reactive({
  year: '',
  month: '',
  desc: '', // 截止2024年12月
  monthStatistics: {
    withCity: 0,
    internationalHk: 0, // 国际港澳台
    remoteLocation: 0, // 异地
    orderSalesNewspaper: 0, // 订销报纸
    letters: 0, // 函件
    packageNum: 0, // 包裹
    orderSalesMagazine: 0, // 订销杂志
  },
})

/** 邮政概况-快递业务寄件量 */
let kdywjjblOptions = reactive({
  title: {
    ...utils.generateChartTitle('年度快递业务寄件分类'),
    top: '0%',
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
    // backgroundColor: 'rgba(0,0,0,0.7)',
    borderColor: 'rgba(255,255,255,0.3)',
    textStyle: {
      // color: '#fff',
      fontSize: 14,
    },
  },
  legend: [
    {
      orient: 'vertical', // 垂直排列
      right: 'right', // 图例放在左侧
      top: 'middle', // 垂直居中
      data: ['同城', '异地', '国际港澳台'], // 左侧显示前半部分
      itemGap: 8, // 减小图例间距
      itemWidth: 10, // 减小图例标记的宽度
      itemHeight: 10, // 减小图例标记的高度
      textStyle: {
        fontSize: 14, // 减小图例文字大小
      },
      formatter: function (name) {
        const data = [
          { name: '同城', total: yzgk.monthStatistics?.withCity || 0 },
          { name: '异地', total: yzgk.monthStatistics?.remoteLocation || 0 },
          { name: '国际港澳台', total: yzgk.monthStatistics?.internationalHk || 0 },
        ]
        const item = data.find((d) => d.name === name)
        if (!item) return ''
        const total = data.reduce((sum, cur) => sum + cur.total, 0)
        const percentage = total > 0 ? ((item.total / total) * 100).toFixed(1) : 0
        return `${name} ${percentage}%`
      },
    },
  ],
  series: [
    {
      name: '快递业务寄件量',
      type: 'pie',
      radius: '60%',
      left: '0%',
      data: [
        { value: yzgk.monthStatistics.withCity, name: '同城' },
        { value: yzgk.monthStatistics.remoteLocation, name: '异地' },
        { value: yzgk.monthStatistics.internationalHk, name: '国际港澳台' },
      ],
      label: {
        show: false, // 关闭指示线
      },
      labelLine: {
        show: false, // 关闭指示线
      },
      color: ['#4282ff', '#37e0cc', '#ff7070', '#ffd66b', '#a26cf8'],
    },
  ],
})

/** 邮政概况-邮政普邮寄件量 */
const yzpbfwjjblOptions = reactive({
  title: {
    ...utils.generateChartTitle('邮政普邮寄件分类'),
    top: '0%',
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
    // backgroundColor: 'rgba(0,0,0,0.7)',
    borderColor: 'rgba(255,255,255,0.3)',
    textStyle: {
      // color: '#fff',
      fontSize: 14,
    },
  },
  legend: [
    {
      orient: 'vertical', // 垂直排列
      right: 'right', // 图例放在左侧
      top: 'middle', // 垂直居中
      data: ['普邮函件', '普邮包裹'], // 左侧显示前半部分
      itemGap: 8, // 减小图例间距
      itemWidth: 10, // 减小图例标记的宽度
      itemHeight: 10, // 减小图例标记的高度
      textStyle: {
        fontSize: 14, // 减小图例文字大小
      },
      formatter: function (name) {
        const data = [
          { name: '普邮函件', total: yzgk.monthStatistics?.letters || 0 },
          { name: '普邮包裹', total: yzgk.monthStatistics?.packageNum || 0 },
        ]
        const item = data.find((d) => d.name === name)
        if (!item) return ''
        const total = data.reduce((sum, cur) => sum + cur.total, 0)
        const percentage = total > 0 ? ((item.total / total) * 100).toFixed(1) : 0
        return `${name} ${percentage}%`
      },
    },
  ],
  series: [
    {
      name: '邮政普邮寄件量',
      type: 'pie',
      radius: '60%',
      left: '0%',
      data: [
        { value: yzgk.monthStatistics.letters, name: '普邮函件' },
        { value: yzgk.monthStatistics.packageNum, name: '普邮包裹' },
      ],
      label: {
        show: false, // 关闭指示线
      },
      labelLine: {
        show: false, // 关闭指示线
      },
      color: utils.genColors(),
    },
  ],
})

/** 年度快递业务量 */
const yzhyywsrOptions = reactive({
  title: {
    text: '年度快递业务量',
    left: 'center',
    top: '10%',
    textStyle: {
      fontSize: 16,
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    orient: 'horizontal',
    bottom: '5%',
    itemGap: 3,
    itemWidth: 10,
    itemHeight: 10,
    textStyle: {
      fontSize: 12,
    },
    data: ['同城', '异地', '国际港澳台'],
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    axisLabel: {
      fontSize: 12,
    },
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
  },
  yAxis: {
    type: 'value',
    name: '万件',
    nameLocation: 'end',
    axisLabel: {
      fontSize: 12,
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)',
      },
    },
  },
  grid: {
    top: '26%',
    left: '2%',
    right: '2%',
    bottom: '15%',
    containLabel: true,
  },
  series: [
    {
      name: '同城',
      data: [],
      type: 'bar',
      // stack: 'total',
      color: '#336bd3',
      barWidth: '30%',
    },
    {
      name: '异地',
      data: [],
      type: 'bar',
      // stack: 'total',
      color: '#37e0cc',
      barWidth: '30%',
    },
    {
      name: '国际港澳台',
      data: [],
      type: 'bar',
      // stack: 'total',
      color: '#FF0000',
      barWidth: '30%',
    },
  ],
})

/** 铁路货运量 */
function initTlhylOptions() {
  const chartDom = document.getElementById('tlhyl')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(tlhylOptions, { notMerge: true })
}

/** 铁路车皮量 */
function initTlcplOptions() {
  const chartDom = document.getElementById('tlcpl')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(tlcplOptions, { notMerge: true })
}

/** 航空货邮吞吐量 */
function initHkhyttlOptions() {
  const chartDom = document.getElementById('hkhyttl')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(hkhyttlOptions, { notMerge: true })
}

/** 公路货运量 */
function initGlhylOptions() {
  const chartDom = document.getElementById('glhyl')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(glhylOptions, { notMerge: true })
}

/** 邮政快递业务寄件量 */
function initKdywjjblOptions() {
  const chartDom = document.getElementById('kdywjjbl')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(kdywjjblOptions, { notMerge: true })
}

/** 邮政普邮寄件量 */
function initYzpbfwjjblOptions() {
  const chartDom = document.getElementById('yzpbfwjjbl')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(yzpbfwjjblOptions, { notMerge: true })
}

/** 邮政行业业务收入 */
function initYzhyywsrOptions() {
  const chartDom = document.getElementById('yzhyywsr')
  if (!chartDom) return
  let myChart = echarts.getInstanceByDom(chartDom)
  if (!myChart) {
    myChart = echarts.init(chartDom)
  }

  myChart.setOption(yzhyywsrOptions, { notMerge: true })
}

const colors = utils.genColors()

/** 加载铁路数据 */
async function loadTlData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }
  try {
    let year, month
    if (tlgk.year && tlgk.month) {
      year = tlgk.year
      month = tlgk.month
    } else {
      const getNewestDataRes = await Apis.szbt.railway.get_getNewestData()
      ;({ year, month } = utils.parseDate(getNewestDataRes.newestDate))
    }
    tlgk.year = year.toString()
    tlgk.month = month.toString()

    tlgk.desc = `截止${year}年${month}月`

    const getChartDataRes = await Apis.szbt.railway.get_getChartData({
      params: {
        year: year,
        month: month,
      },
    })

    tlgk.monthStatistics = getChartDataRes.monthStatistics

    const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')
    {
      tlhylOptions.series[0].data = getChartDataRes.months
        .filter((item) => item.year == year)
        .sort((a, b) => a.month - b.month)
        .map((item) => {
          return {
            value: item.loadingTotalWeight,
            name: item.month,
          }
        })

      tlhylOptions.series[1].data = getChartDataRes.months
        .filter((item) => item.year == year)
        .sort((a, b) => a.month - b.month)
        .map((item) => {
          return {
            value: item.unloadTotalWeight,
            name: item.month,
          }
        })

      tlhylOptions.series[2].data = getChartDataRes.months
        .filter((item) => item.year == year)
        .sort((a, b) => a.month - b.month)
        .map((item) => {
          return {
            value: item.cpCount,
            name: item.month,
          }
        })
      console.log(tlhylOptions.series, 'tlhylOptions.series[2]--++++')
    }
    {
      const series: any[] = []
      Object.keys(groupedData).forEach((year, index) => {
        // 找当年的
        series.push({
          name: `${year}年`,
          type: 'line',
          // stack: 'Total',
          showSymbol: false,
          smooth: true,
          areaStyle: {
            opacity: 0.15,
          },
          emphasis: {
            focus: 'series',
          },
          color: colors[index],
          data: groupedData[year].map((item) => {
            return {
              value: item.cxCount,
              name: item.month + '月',
            }
          }),
        })
      })

      tlcplOptions.series = series
      tlcplOptions.legend.data = sortedKeys.map((year) => `${year}年`)
      console.log(tlcplOptions.series, 'tlcplOptions.series---------------')

      const maxData = []
      tlcplOptions.series.map((item: any) => {
        item.data.map((v: any) => {
          maxData.push(v.value)
        })
      })
      const maxVal = Math.max(...maxData)
      const yMax = roundUpToPrecision(maxVal)
      tlcplOptions.yAxis.max = yMax
      tlcplOptions.yAxis.splitNumber = 5
    }
    initTlhylOptions()
    initTlcplOptions()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}
// 智能大数向上取整
function roundUpToPrecision(num: number, precision = 10000) {
  return Math.ceil(num / precision) * precision
}
/** 加载航空数据 */
async function loadHkData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }
  try {
    let year, month
    if (hkgk.year && hkgk.month) {
      year = hkgk.year
      month = hkgk.month
    } else {
      const getNewestDataRes = await Apis.szbt.aviationTransportData.get_getNewestData()
      ;({ year, month } = utils.parseDate(getNewestDataRes.newestDate))
    }
    hkgk.year = year.toString()
    hkgk.month = month.toString()

    hkgk.desc = `截止${year}年${month}月`

    const getChartDataRes = await Apis.szbt.aviationTransportData.get_getChartData({
      params: {
        year: year,
        month: month,
      },
    })

    hkgk.monthStatistics = getChartDataRes.monthStatistics

    // 计算同比增长率
    const freightAndThroughputYoy = calcYearOverYear(
      hkgk.monthStatistics.freightAndThroughput,
      hkgk.monthStatistics.qnFreightAndThroughput,
    )

    hkgk.freightAndThroughputYoy = freightAndThroughputYoy

    const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')

    {
      hkhyttlOptions.legend.data = sortedKeys.map((item) => item + '年')

      const series: any[] = []
      Object.keys(groupedData).forEach((year, index) => {
        series.push({
          name: `${year}年`,
          type: 'line',
          radius: '100%',
          smooth: true,
          symbolSize: 2,
          lineStyle: {
            width: 2,
          },
          color: colors[index],
          data: groupedData[year].map((item) => {
            return {
              value: item.freightAndThroughput,
              name: item.month + '月',
            }
          }),
        })
      })
      hkhyttlOptions.series = series
      const maxData = []
      hkhyttlOptions.series.map((item: any) => {
        item.data.map((v: any) => {
          maxData.push(v.value)
        })
      })
      const maxVal = Math.max(...maxData)
      const yMax = roundUpToPrecision(maxVal, 10)
      hkhyttlOptions.yAxis.max = yMax
      hkhyttlOptions.yAxis.splitNumber = 4
    }
    initHkhyttlOptions()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

// 计算同比增长率
const calcYearOverYear = (current: number, lastYear: number) => {
  if (isNaN(current) || isNaN(lastYear)) return '/' // 防止NaN
  if (!lastYear) return '/'
  const result = ((current - lastYear) / lastYear) * 100
  return isNaN(result) ? 0 : Number(result.toFixed(2)) // 再次检查NaN
}

/** 加载公路数据 */
async function loadGlData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }
  try {
    let year, month
    if (glgk.year && glgk.month) {
      year = glgk.year
      month = glgk.month
    } else {
      const getNewestDataRes = await Apis.szbt.highwayTransportData.get_getNewestData()
      ;({ year, month } = utils.parseDate(getNewestDataRes.newestDate))
    }
    glgk.year = year.toString()
    glgk.month = month.toString()

    glgk.desc = `截止${year}年${month}月`
    const getChartDataRes = await Apis.szbt.highwayTransportData.get_getChartData({
      params: {
        year: year,
        month: month,
      },
    })

    glgk.monthStatistics = getChartDataRes.monthStatistics

    // 计算同比增长率
    const theVolumeYoy = calcYearOverYear(
      glgk.monthStatistics.theVolume,
      glgk.monthStatistics.qnTheVolume,
    )

    const goodsTurnoverVolumeYoy = calcYearOverYear(
      glgk.monthStatistics.goodsTurnoverVolume,
      glgk.monthStatistics.qnGoodsTurnoverVolume,
    )

    glgk.theVolumeYoy = theVolumeYoy
    glgk.goodsTurnoverVolumeYoy = goodsTurnoverVolumeYoy

    const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')

    {
      glhylOptions.legend.data = sortedKeys.map((item) => item + '年')

      const series: any[] = []
      Object.keys(groupedData).forEach((year, index) => {
        series.push({
          name: `${year}年`,
          type: 'line',
          radius: '100%',
          smooth: true,
          symbolSize: 2,
          lineStyle: {
            width: 2,
          },
          color: colors[index],
          data: groupedData[year].map((item) => {
            return {
              value: item.theVolume,
              name: item.month + '月',
            }
          }),
        })
      })
      glhylOptions.series = series
      const maxData = []
      glhylOptions.series.map((item: any) => {
        item.data.map((v: any) => {
          maxData.push(v.value)
        })
      })
      const maxVal = Math.max(...maxData)
      const yMax = roundUpToPrecision(maxVal, 10)
      glhylOptions.yAxis.max = yMax
      glhylOptions.yAxis.splitNumber = 4
    }

    initGlhylOptions()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}

/** 加载邮政数据 */
async function loadYzData(isInit = false) {
  if (!isInit) {
    bigScreenStore.showLoading()
  }
  try {
    let year, month
    if (yzgk.year && yzgk.month) {
      year = yzgk.year
      month = yzgk.month
    } else {
      const getNewestDataRes = await Apis.szbt.postData.get_getNewestData()
      ;({ year, month } = utils.parseDate(getNewestDataRes.newestDate))
    }
    yzgk.year = year.toString()
    yzgk.month = month.toString()

    const getChartDataRes = await Apis.szbt.postData.get_getChartData({
      params: {
        year: year,
        month: month,
      },
    })

    yzgk.desc = `截止${year}年${month}月`

    yzgk.monthStatistics = getChartDataRes.monthStatistics
    yzgk.monthStatistics.withCity = yzgk.monthStatistics?.withCity || 0

    yzgk.monthStatistics.remoteLocation = yzgk.monthStatistics?.remoteLocation || 0

    yzgk.monthStatistics.internationalHk = yzgk.monthStatistics?.internationalHk || 0

    yzgk.monthStatistics.letters = yzgk.monthStatistics?.letters || 0

    yzgk.monthStatistics.packageNum = yzgk.monthStatistics?.packageNum || 0

    yzgk.monthStatistics.orderSalesNewspaper = yzgk.monthStatistics?.orderSalesNewspaper || 0

    yzgk.monthStatistics.orderSalesMagazine = yzgk.monthStatistics?.orderSalesMagazine || 0

    kdywjjblOptions.series[0].data = [
      { name: '同城', value: yzgk.monthStatistics?.withCity || 0 },
      { name: '异地', value: yzgk.monthStatistics?.remoteLocation || 0 },
      { name: '国际港澳台', value: yzgk.monthStatistics?.internationalHk || 0 },
    ]

    yzpbfwjjblOptions.series[0].data = [
      { value: yzgk.monthStatistics.letters || 0, name: '普邮函件' },
      { value: yzgk.monthStatistics.packageNum || 0, name: '普邮包裹' },
    ]

    // kdywjjblOptions.legend[0].formatter = (name: string) => {
    //   const data = [
    //     { name: '同城', total: (yzgk.monthStatistics?.withCity || 0) },
    //     { name: '异地', total: (yzgk.monthStatistics?.remoteLocation || 0) },
    //     { name: '国际港澳台', total: (yzgk.monthStatistics?.internationalHk || 0) },
    //   ]
    //   const item = data.find((d) => d.name === name)
    //   if (!item) return ''
    //   const total = data.reduce((sum, cur) => sum + cur.total, 0)
    //   const percentage = total > 0 ? ((item.total / total) * 100).toFixed(1) : 0
    //   return `${name} (${item.total}, ${percentage}%)`
    // }
    // const { groupedData, sortedKeys } = utils.groupAndSortByField(getChartDataRes.months, 'year')
    yzhyywsrOptions.series[0].data = getChartDataRes.months
      .filter((item) => item.year == year)
      .sort((a, b) => a.month - b.month)
      .map((item) => {
        return {
          value: item?.withCity || 0,
          name: item.month,
        }
      })

    yzhyywsrOptions.series[1].data = getChartDataRes.months
      .filter((item) => item.year == year)
      .sort((a, b) => a.month - b.month)
      .map((item) => {
        return {
          value: item?.remoteLocation || 0,
          name: item.month,
        }
      })

    yzhyywsrOptions.series[2].data = getChartDataRes.months
      .filter((item) => item.year == year)
      .sort((a, b) => a.month - b.month)
      .map((item) => {
        return {
          value: item?.internationalHk || 0,
          name: item.month,
        }
      })
    const maxData = []
    yzhyywsrOptions.series.map((item: any) => {
      item.data.map((v: any) => {
        maxData.push(v.value)
      })
    })
    const maxVal = Math.max(...maxData)
    const yMax = roundUpToPrecision(maxVal, 10)
    yzhyywsrOptions.yAxis.max = yMax
    yzhyywsrOptions.yAxis.splitNumber = 4
    initKdywjjblOptions()
    initYzpbfwjjblOptions()
    initYzhyywsrOptions()
  } catch (error) {
  } finally {
    if (!isInit) {
      bigScreenStore.hideLoading()
    }
  }
}
// 查看明细
const opanDetail = (text: string) => {
  switch (text) {
    case '铁路货运':
      tlhylModalRef.value?.setData({
        params: {
          year: tlgk.year,
        },
      })
      tlhylModalRef.value?.open()
      break
    case '航空货运':
      hkttlModalRef.value?.setData({
        params: {
          year: hkgk.year,
        },
      })
      hkttlModalRef.value?.open()
      break
    case '公路货运':
      glhylModalRef.value?.setData({
        params: {
          year: glgk.year,
        },
      })
      glhylModalRef.value?.open()
      break
    case '邮政快递':
      yzsyqkModalRef.value?.setData({
        params: {
          year: yzgk.year,
        },
      })
      yzsyqkModalRef.value?.open()
      break

    default:
      break
  }
}
/** 加载数据 */
async function loadData() {
  bigScreenStore.showLoading()

  try {
    await Promise.all([loadTlData(), loadHkData(), loadGlData(), loadYzData()])
  } catch (error) {
  } finally {
    bigScreenStore.hideLoading()
  }
}

onMounted(async () => {
  await loadData()

  // initTlhylOptions()
  // initTlcplOptions()
  // initHkhyttlOptions()
  // initGlhylOptions()
  // initKdywjjblOptions()
  // initYzpbfwjjblOptions()
  // initYzhyywsrOptions()

  // initsrgkByXbblChart()
  // initsrgkByQyzbChart()
  // initsrgkByZsChart()
  // initTxsjByMonthChart()
  // initZdxxsgkByOptionsChart()
  // initKylqkByOptionsChart()
  // initTlsjByOptionsChart()
  // initGlsjByOptionsChart()
  // initLkzlByOptionsChart()
  // initJgkzlByOptionsChart()
  // initCgkzlByOptionsChart()
  // initJnkzlByOptionsChart()
  // initJwkzlByOptionsChart()
  emit('mounted')
})
</script>

<style scoped>
div {
  box-sizing: border-box;
}
.text-md {
  color: #999;
}
.unit {
  font-size: 12px;
  color: #999999;
  margin-left: 5px;
}
.valueNum-zf {
  color: #00bcc3;
}
.a-row-box {
  min-height: calc(100vh - 220px) !important;
}
</style>
